package cn.cellcom.agent.online.dispatcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cellcom.agent.online.client.AgentClient;
import cn.cellcom.agent.online.client.ClientManager;
import cn.cellcom.agent.online.wrapper.SessionWrapper;
import cn.cellcom.agent.util.RedisManager;

public class LastAgentSelector extends AbstractAgentSelector {
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	public AgentClient bestAgentFrom(SessionWrapper session) {
		List<AgentClient> validateList = new ArrayList<AgentClient>();
		Set<AgentClient> agents = ClientManager.getInstance().getOnlineAgents(session.getPid());
		if (agents != null) {
			for (AgentClient ac : agents) {
				boolean validate = super.validateAgent(ac, session);
				if (validate) {
					validateList.add(ac);
				}
			}
		}

		if (validateList.size() == 0) {
			return null;
		}
		// 查找上次服务坐席
		String lastAgent = RedisManager.getInstance().getLastAgent().getString(session.getVisitor().getId() + "--" + session.getPid());
		if (StringUtils.isNotBlank(lastAgent)) {
			for (int i = 0; i < validateList.size(); i++) {
				AgentClient v = validateList.get(i);
				if (v.getId().equals(lastAgent)) {
					log.info("[{}] 's session[{}] find the last agent[{}]", session.getVisitor().getId(), session.getId(), v.getId() + "/"
							+ v.getAgent().getNickName());
					return validateList.get(i);
				}
			}
		}
		return validateList.get(new Random().nextInt(validateList.size()));
	}

}
